package com.demo.auth.service;

import com.demo.auth.dao.domain.AuthCodeUser;
import com.demo.auth.entity.AdminUserDetails;
import com.demo.common.constants.AuthModel;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AuthenticationTokenService {

    @Resource(name = "jdbcClientDetailsService")
    private ClientDetailsService clientDetailsService;

    public UsernamePasswordAuthenticationToken initUsernamePasswordAuthenticationToken(String clientId) {
        ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
        UserDetails user = User.withUsername(clientDetails.getClientId())
                .password(clientDetails.getClientSecret())
                .authorities(clientDetails.getAuthorities())
                .build();

        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());
        usernamePasswordAuthenticationToken.eraseCredentials();
        return usernamePasswordAuthenticationToken;
    }

    public UsernamePasswordAuthenticationToken initUsernamePasswordAuthenticationToken(AuthCodeUser user) {
        AdminUserDetails adminUserDetails = new AdminUserDetails(user.getId(), user.getUserName(), "", AuthModel.AUTHORIZATION_CODE, List.of());
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(adminUserDetails, adminUserDetails.getPassword(), adminUserDetails.getAuthorities());
        usernamePasswordAuthenticationToken.eraseCredentials();
        return usernamePasswordAuthenticationToken;
    }
}
